
const appGlobal = function () {
  let ws;

  //url -> “ws://localhost:8080”
  appGlobal.prototype.init = function (url, openCallback, receiveCallback, closeCallback) {
    ws = new WebSocket(url);

    //回调函数,连接后触发
    if (typeof openCallback === "function") {
      ws.onopen = function () {
        openCallback();
      };
    }
    //回调函数,接收数据后就触发
    if (typeof receiveCallback === "function") {
      ws.onmessage = function (evt) {
        receiveCallback(evt.data);
      };
    }

    //回调函数,ws关闭触发
    if (typeof closeCallback === "function") {
      ws.onclose = function (evt) {
        closeCallback(evt.data);
      };
    }
    setInterval(function () {
      ws.send("@");
    },5000);
  }

  appGlobal.prototype.sendMsg = function (msg, callback) {
    ws.send(msg);
    //ws关闭触发
    if (typeof callback === "function") {
      callback();
    }
  }

  appGlobal.prototype.sendMsg = function (msg) {
    ws.send(msg);
  }
}

export function app() {

  //采用prototype原型实现方式，查找元素在数组中的索引值
  Array.prototype.getArrayIndex=function(obj){
    for(var i=0;i<this.length;i++){
      if(this[i]===obj){
        return i;
      }
    }
    return -1;
  }

  return new appGlobal();
}
